using System.Reflection;
using Mbs.ComponentModel.Container.Context;
using Mbs.Reflection;

namespace Mbs.ComponentModel.Container.Injection
{
    
    public class FieldInject : InjectAdapter<FieldInfo>
    {
        protected override void DoExecute(IInjectContext<FieldInfo> ctx)
        {
            if (ctx.Members == null
                || ctx.Members.Length == 0
                || ctx.Instance == null)
                return;

            foreach (var pair in ctx.Members)
                SetFieldValue(pair.Key, ctx.Instance, pair.Value);
        }

        protected virtual void SetFieldValue(FieldInfo fi, object instance, string id)
        {
            if (!string.IsNullOrEmpty(id))
                fi.Set(instance, Kernel.Get(id));
            else
                fi.Set(instance, Kernel.Get(fi.FieldType));
        }
    }
}
